package com.lw.sbdemo2.service;

import com.github.pagehelper.PageHelper;
import com.lw.sbdemo2.common.base.CrudService;
import com.lw.sbdemo2.common.constant.TkConstants;
import com.lw.sbdemo2.common.exception.ApiException;
import com.lw.sbdemo2.common.utils.IdUtils;
import com.lw.sbdemo2.common.vo.PageInfo;
import com.lw.sbdemo2.entity.TkOrderRecord;
import com.lw.sbdemo2.entity.TkUserExamRecord;
import com.lw.sbdemo2.entity.TkUserInfo;
import com.lw.sbdemo2.mapper.TkOrderRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>标题: 订单记录表服务 - 业务逻辑层</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2019</p>
 * <p>公司: 山人行工作室</p>
 *
 * @version: 1.0
 * @author: LinWang
 * @date 2019-4-14
 */
@Slf4j
@Service
public class TkOrderRecordService extends CrudService<TkOrderRecord, TkOrderRecordMapper> {

    /**
     * 用户信息表服务
     */
    @Autowired
    private TkUserInfoService tkUserInfoService;

    /**
     * 用户试卷记录表服务
     */
    @Autowired
    private TkUserExamRecordService tkUserExamRecordService;

    /**
     * 创建订单
     */
    @Transactional(rollbackFor = Exception.class)
    public String orderCreate(TkOrderRecord tkOrderRecord) {

        //唯一订单ID
        String orderId = IdUtils.createOrderNo();

        TkUserExamRecord tkUserExamRecord = new TkUserExamRecord();
        tkUserExamRecord.setUserId(tkOrderRecord.getUserId());
        tkUserExamRecord.setExamId(tkOrderRecord.getExamId());
        List<TkUserExamRecord> tkUserExamRecords = tkUserExamRecordService.findList(tkUserExamRecord);
        if (tkUserExamRecords.size() > 0) {
            throw new ApiException("已拥有该试卷，不可重复购买~");
        }

        TkUserInfo tkUserInfo = tkUserInfoService.getById(tkOrderRecord.getUserId());
        if (tkUserInfo != null) {
            tkOrderRecord.setUserName(tkUserInfo.getUserName());
        }

        //订单主表操作
        tkOrderRecord.setOrderId(orderId);
        tkOrderRecord.setValidFlag("1");
        tkOrderRecord.setCreatedTime(new Date());
        tkOrderRecord.setOrderStatus(TkConstants.ORDER_STATUS_NEW);
        this.insert(tkOrderRecord);

        return orderId;
    }

    /**
     * 获取用户分页列表
     *
     * @param query         搜索关键词
     * @param pageInfo      分页实体
     * @param tkOrderRecord 实体入参
     * @return 用户列表
     */
    public PageInfo<TkOrderRecord> findListPage(String query, PageInfo pageInfo, TkOrderRecord tkOrderRecord) {
        PageHelper.startPage(pageInfo);
        List<TkOrderRecord> tkOrderRecordlist = this.dao.findListPage(query, tkOrderRecord);
        return new PageInfo<>(tkOrderRecordlist);
    }
}
